<!--
 * @Author: xuwejie 1529315455@qq.com
 * @Date: 2023-08-28 14:39:14
 * @LastEditors: xuwejie 1529315455@qq.com
 * @LastEditTime: 2023-09-08 17:01:04
 * @FilePath: \v9\src\views\marketing\marketingFullAdd\marketingFull_reduce.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <el-form
      class="demo-form-inline"
      :model="form"
      label-width="110px"
      :rules="rules"
      ref="form"
    >
      <div class="container">
        <div class="add_container">
          <el-form-item label="活动名称：" prop="name">
            <el-input
              class="wid240"
              v-model.trim="form.name"
              placeholder="活动名称"
              @change="isEdit = true"
            ></el-input>
          </el-form-item>
          <el-form-item label="活动时间：" prop="time">
            <el-date-picker
              v-model.trim="form.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              @change="isEdit = true"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <span slot="label"
              >满减规则
              <el-tooltip class="item" effect="dark" placement="bottom">
                <div slot="content">
                  后面一条的满金额，减金额都必须比上一条大
                </div>
                <i class="el-icon-question"></i></el-tooltip
              >:</span
            >

            <div class="rule" v-for="(item, index) in rule_list" :key="index">
              消费满
              <el-input-number
                v-model="item.price"
                :controls="false"
                :min="item.min_price"
                :precision="2"
              ></el-input-number>
              元，减
              <el-input-number
                v-model="item.reduce"
                :min="item.min_reduce"
                :controls="false"
                :precision="2"
              ></el-input-number>
              元
              <span class="rule_delete" v-if="index != 0"
                ><i class="el-icon-close" @click="reduceRules(index)"></i
              ></span>
            </div>
            <div class="rule">
              <el-button
                type="primary"
                @click="addRules"
                :class="{ addrule_btn: rule_list.length >= 3 }"
              >
                <i class="el-icon-plus"></i>
                添加满减规则(最多3条)
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="商品限制：" prop="goods_limit">
            <el-radio-group v-model="form.goods_limit" @change="isEdit = true">
              <el-radio :label="0">不限制</el-radio>
              <el-radio :label="1">部分商品</el-radio>
              <el-radio :label="2">排除商品</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="goods_container" v-show="goods_table_show">
          <div class="goods_container_header">
            <el-form-item label="商品名称：">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                @click="openShopList"
                >选择商品</el-button
              >
              <!-- <el-autocomplete
                v-model="goods_name"
                ref="searchSelect"
                class="wid240 main_comm"
                :trigger-on-focus="true"
                @clear="$refs.searchSelect.$children[0].blur()"
                :fetch-suggestions="
                  (queryString, cb) => {
                    querySearchAsync(queryString, cb);
                  }
                "
                placeholder="商品/助记码/编码"
                clearable
                :highlight-first-item="true"
                value-key="name"
                @select="
                  (item) => {
                    handleSelect(item);
                  }
                "
              >
                <template slot-scope="{ item }">
                  <div class="main_name">
                    <span
                      >{{ item.goods.name }}【{{
                        item.spu_name ? item.spu_name.title : ""
                      }}】</span
                    >
                    <span class="main_addr">{{ item.goods_spu_code }}</span>
                  </div>
                </template>
              </el-autocomplete> -->
            </el-form-item>
          </div>
          <div class="goods_container_body main_table">
            <el-table
              ref="multipleTable"
              :data="list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
            >
              <el-table-column label="序号">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goods_name"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.goods_name }}【{{ scope.row.spu_name }}】
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="单位"
                prop="unit"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="市场价"
                prop="price"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="管理操作"
                prop="name"
                width="220"
                align="center"
                fixed="right"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-link @click="handeleDel(scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div
          :class="['save_container', { positive: searchBarFixed }]"
          id="newConBox"
        >
          <el-button
            type="primary"
            @click="preservation"
            v-repeatClick
            :loading="loading"
            >保存</el-button
          >
          <el-button @click="$router.back(-1)">取消</el-button>
        </div>
      </div>
    </el-form>

    <el-dialog title="勾选商品" :visible.sync="shopListDialog" width="80%">
      <el-form
        ref="shopCondition"
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-select
            v-model="formInline.region"
            clearable
            placeholder="一级分类"
          >
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="formInline.region"
            clearable
            placeholder="二级分类"
          >
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="商品名称/编号/助记码"
            v-model="formInline.input2"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="reset">重置</el-button>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="shopListTable"
        :data="tableData"
        border
        v-loading="loadingDialig"
        tooltip-effect="dark"
        style="width: 100%"
        :row-key="getRowKeys"
      >
        <el-table-column width="55" :reserve-selection="true">
          <template slot="header" slot-scope="scope">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleSelectionChange"
            ></el-checkbox>
          </template>
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.check"
              @change="handRow(scope.row, scope.$index, $event)"
              :disabled="scope.row.disabled"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          label="商品名称"
          align="center"
          width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column prop="name" label="单位" align="center">
        </el-table-column>
        <el-table-column
          prop="address"
          label="最近一次采购价"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="address"
          label="市场价"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column width="200" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.disabled"
              type="text"
              @click="addDom(scope.$index)"
              >添加</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagi.page"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pagi.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totle"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shopListDialog = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>

      <!-- <el-dialog
        width="30%"
        title="选择勾选页签"
        :visible.sync="innerVisible"
        append-to-body
      >
        <div class="tab-box">
          <div class="item">
            <span class="item-title">当前页</span>
            <span class="item-tip">只勾选当前页的商品</span>
          </div>
          <div class="item">
            <span class="item-title">所有页面</span>
            <span class="item-tip">勾选列表上所有商品</span>
          </div>
        </div>
      </el-dialog> -->
    </el-dialog>
  </div>
</template>

<script>
import rules from "@/rules/marketing/marketing_full.js";
import {
  get_full_add,
  get_full_getGoodsSpu,
} from "@/api/marketing/marketing.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";

// 获取商品列表
import { goods_index } from "@/api/commodity/commodityList";
export default {
  data() {
    let id = 0;
    return {
      rules,
      num: 0,
      // 商品list
      list: [],
      // 监听滚动
      searchBarFixed: false,
      form: {
        name: "",
        start_time: "",
        end_time: "",
        goods_limit: null,
        time: [],
        type: 1, //满减满赠类型  type1  满减  2 满赠
      },
      // 活动时间
      time: [],
      //规则
      rule_list: [
        {
          price: 0,
          reduce: 0,
          min_reduce: 0,
          min_price: 0,
        },
      ],
      focus_num: "",
      goods_table_show: false,
      goods_name: "",
      loading: false,
      pickerOptions: {
        disabledDate(time) {
          let now = new Date();
          now.setHours(0);
          now.setMinutes(0);
          now.setSeconds(0);
          now.setMilliseconds(0);
          return time.getTime() < now.getTime();
        },
      },
      isEdit: false,

      props: {
        lazy: true,
        lazyLoad: this.getLists,
      },

      // 控制选择商品模态框
      shopListDialog: false,
      // 控制选择商品模态框的全选时触发的模态框
      innerVisible: false,
      // 商品模态框的表单
      formInline: {},
      // 商品模态框的表格
      tableData: [],
      loadingDialig: false,

      pagi: {
        page: 1,
        pageSize: 10,
      },
      totle: 0,
      checkAll: false,
      isIndeterminate: false,

      // 点击每行的多选框后激活的数据列表
      rowActiveList: [],
    };
  },
  watch: {
    "form.goods_limit": {
      handler(val) {
        if (val) this.goods_table_show = true;
        else this.goods_table_show = false;

        // 当选中指定分类时，需要将之前所选的商品清空
        if (val == 3) {
          this.list = [];
        }
      },
      deep: true,
      immediate: true,
    },
    tableData: {
      handler(val) {
        let someStatusCount = 0;
        val.forEach((item) => {
          if (item.check === true) {
            someStatusCount++;
          }
        });
        this.checkAll = someStatusCount === 0 ? false : true;
        this.isIndeterminate =
          someStatusCount > 0 && someStatusCount < val.length;
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 监听滚动
    handleScroll() {
      return;
      let de = document.getElementById("newConBox");
      let de_top = de.getBoundingClientRect().top;
      let de_height = de.getBoundingClientRect().height;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      de_top + de_height + 80 >
      scrollTop + document.documentElement.clientHeight
        ? (this.searchBarFixed = true)
        : (this.searchBarFixed = false);
      //   console.log(
      //     scrollTop + document.documentElement.clientHeight,
      //     de_top + de_height + 80
      //   );
    },
    getLists(node, resolve) {
      this.getData(node, resolve);
    },
    async getData(node, resolve) {
      let that = this;
      let level = node.level;
      console.log(level, node.data);
      if (!node.data) {
        // await this.Api.vaccName().then((res) => {
        //   //接口
        //   const nodes = Array.from(res.data).map((item) => ({
        //     value: item.goodsCode,
        //     label: `${item.goodsName}`,
        //     leaf: level >= 1,
        //   }));
        //   // 通过调用resolve将子节点数据返回，通知组件数据加载完成
        //   resolve(nodes);
        // });
      } else {
        // await this.Api.vaccNameChild({ goodsCode: node.data.value }).then(
        //   (res) => {
        //     const nodes = Array.from(res.data).map((item) => ({
        //       value: item.goodsCode,
        //       label: `${item.goodsName}`,
        //       leaf: level >= 1,
        //     }));
        //     // 通过调用resolve将子节点数据返回，通知组件数据加载完成
        //     resolve(nodes);
        //   }
        // );
      }
    },
    // 添加规则
    addRules() {
      let length = this.rule_list.length;
      if (this.rule_list.length < 3) {
        this.rule_list.push({
          price: this.rule_list[length - 1].price + 0.01,
          reduce: this.rule_list[length - 1].reduce + 0.01,
          min_reduce: this.rule_list[length - 1].min_reduce + 0.01,
          min_price: this.rule_list[length - 1].price + 0.01,
        });
      } else {
        return;
      }
    },
    // 减少规则
    reduceRules(index) {
      this.rule_list.splice(index, 1);
    },

    // 获取商品
    querySearchAsync(queryString, cb) {
      let name = queryString || "";
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: name,
          status: 1,
        }
      );
      get_full_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          var results = res.data.list;
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.isEdit = true;
      let obj = {
        goods_id: item.goods_id,
        goods_spu_id: item.id,
        goods_name: item.goods.name,
        spu_name: item.spu_name.title,
        unit: item.spu_unit.title,
        price: item.market_price,
      };
      let flag = false;
      this.list.map((e) => {
        if (e.goods_spu_id == item.id) {
          flag = true;
        }
      });
      if (!flag) {
        this.list.push(obj);
      }
    },
    handeleDel(index) {
      this.list.splice(index, 1);
      this.isEdit = true;
    },
    // 保存
    preservation() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let form = this.list_form();
          if (!form) {
            return;
          }
          let goods_data = JSON.parse(form.goods_data);
          let goods_limit = form.goods_limit;
          if (goods_limit != 0 && goods_data.length == 0) {
            this.$message.error("请添加商品");
            return;
          }
          this.loading = true;
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            form
          );
          get_full_add(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("添加成功");
              this.loading = false;
              this.form = {
                name: "",
                start_time: "",
                end_time: "",
                goods_limit: null,
                time: [],
                type: 1,
              };
              this.list = [];
              this.rule_list = [
                {
                  price: 0,
                  reduce: 0,
                  min_reduce: 0,
                  min_price: 0,
                },
              ];
              this.isEdit = false;
              this.$emit("back");
            } else {
              this.$message.warning(res.errmsg);
              this.loading = false;
            }
          });
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = form.time ? form.time[0] : "";
      form.end_time = form.time ? form.time[1] : "";
      delete form.time;
      // goods_data
      form.goods_data = JSON.stringify(this.list);
      let rule = JSON.parse(JSON.stringify(this.rule_list));
      // rule
      rule.map((e) => {
        delete e.min_price;
        delete e.min_reduce;
      });
      let flag = false;
      for (let index = 0; index < rule.length; index++) {
        const e = rule[index];
        if (e.price == 0 || e.reduce == 0) {
          this.$message.error("消费价格,满减价格不能为0");
          flag = true;
          break;
        }
        if (e.price <= e.reduce) {
          this.$message.error("消费价格需要比满减价格大");
          flag = true;
          break;
        }
      }
      form.rule = JSON.stringify(rule);
      return flag ? false : form;
    },
    // 获取商品列表
    getGoodsIndex() {
      return new Promise((resolve, reject) => {
        let data = {
          page: this.pagi.page,
          per_page: this.pagi.pageSize,
        };
        let query = this.packageApi(data);
        get_full_getGoodsSpu(query).then((res) => {
          if (res.errcode == 0) {
            resolve(res.data.list.data);
          } else {
            reject(res.errmsg);
          }
        });
      });
    },

    // 打开选择商品模态框
    async openShopList() {
      /**
       * 1、制空上次通过多选框激活的数据列表
       * 2、打开商品模态框与加载功能
       * 3、调用商品列表接口获取商品列表数据
       * 4、判断list的数据列表中是否存在数据内容，存在，则将商品列表中的状态修改为true，反之赋值为false
       * 5、关闭加载功能
       */
      this.rowActiveList = [];
      this.loadingDialig = true;
      this.shopListDialog = true;
      // let list = await this.getGoodsIndex();
      let list = [
        {
          id: "1",
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          id: "2",
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          id: "3",
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          id: "4",
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          id: "5",
          date: "2016-05-08",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          id: "6",
          date: "2016-05-06",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          id: "7",
          date: "2016-05-07",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
      ];
      this.tableData = this.echoList(list);
      this.loadingDialig = false;
    },
    // 选中的商品回显回模态框
    echoList(list) {
      // 先将获取到的商品数据中添加两个字段，分别是check(是否选中), disabled(是否禁止选中)
      let newList = list.map((item) => {
        item.check = false;
        item.disabled = false;
        return item;
      });
      // 需要回显的数据
      let newEacoList = this._.cloneDeep(this.list);
      // 通过循环将回显中的数据在获取到的列表中状态进行修改
      for (let i = 0; i < newList.length; i++) {
        for (let j = 0; j < newEacoList.length; j++) {
          if (newList[i].id == newEacoList[j].id) {
            newList[i].check = true;
            newList[i].disabled = true;
            break;
          } else continue;
        }
      }
      return newList;
    },
    // 重置商品模态框的搜索条件
    reset() {
      this.$refs.shopCondition.resetFields();
    },
    // 商品模态框的搜索
    onSubmit() {},
    handleAll(e) {
      this.tableData = this.tableData.map((item) => {
        item.check = !item.check;
        return item;
      });
    },
    getRowKeys(row) {
      return row.id;
    },
    handleSizeChange() {},
    handleCurrentChange() {},
    // 单选商品
    handRow(row, index, event) {
      // 获取当前列表长度
      let totalCount = this.tableData.length;
      // 定义当前列表中激活状态的数量
      let someStatusCount = 0;
      this.tableData.forEach((item) => {
        if (item.check === event) {
          someStatusCount++;
        }
      });
      // 当点击勾选时,需将该条数据追加至rowActiveList列表中,反之则从rowActiveList找到该条数据进行剔除
      if (event) this.rowActiveList.push(row);
      else this.rowActiveList.splice(index, 1);
      // 判断当前列表的总长度与激活状态的数量是否一致,一致则激活,反之则关闭
      this.checkAll = totalCount === someStatusCount ? event : !event;
      // 判断多选框是否处于中立状态
      this.isIndeterminate =
        someStatusCount > 0 && someStatusCount < totalCount;
    },
    // 多选商品
    handleSelectionChange(val) {
      this.isIndeterminate = false;
      this.tableData.forEach((item) => {
        if (!item.disabled) item.check = val;
      });
      this.rowActiveList = this._.cloneDeep(this.tableData);
    },
    // 模态框中点击添加
    addDom(index) {
      // 点击添加时,将该条数据的check状态和disabled状态进行变更
      let list = this.tableData[index];
      list.check = true;
      list.disabled = true;
      // 并直接追加至list数组中即可
      this.list.push(list);
    },
    // 完成商品列表的勾选所触发的函数
    save() {
      /**
       * this.list:获取当前已经勾选好的数据列表
       * this.rowActiveList:获取通过左侧勾选的数据列表
       * 将两个数据列表进行合并并深克隆
       * 将最终数据赋值给this.list
       */
      let list = this._.concat(this.list, this.rowActiveList);
      this.list = list;
      this.shopListDialog = false;
    },

    // 封装请求的sign和timeStamp字段
    packageApi(data) {
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      return query;
    },
  },
  created() {},
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 0 20px;
  margin-top: 15px;
}

// 满减规则
.rule {
  display: flex;
  align-items: center;
  &:not(:first-child) {
    margin-top: 10px;
  }
  /deep/.el-input-number {
    width: 80px;
    margin: 0 8px;
  }
  .rule_delete {
    font-size: 20px;
    font-weight: 900;
    margin-left: 15px;
  }
  .addrule_btn {
    cursor: not-allowed;
    background-color: #ebebeb;
    border-color: #ebebeb;
    color: #606266;
  }
}
// 商品限制
/deep/ .el-radio__inner {
  &:hover {
    border-color: #03a98e;
  }
}
.item {
  vertical-align: middle;
  font-size: 16px;
  transform: translateY(-2px);
}

// 商品盒子
.goods_container_header {
  display: flex;
  align-items: flex-start;
  .el-button {
    margin-left: 15px;
  }
}
.goods_container_body {
  padding: 0 20px;
}
.save_container {
  padding: 0 20px;
  margin-top: 15px;
  &.positive {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 9999;
  }
}
.main_name {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 5px 0;
  height: 50px;

  .main_addr {
    color: #999;
  }

  span {
    line-height: 20px;
    display: inline;
    height: 20px;
  }
}

.tab-box {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: 150px;
  gap: 20px;
  .item {
    width: 100%;
    height: 150px;
    border: 1px solid #e1e1e1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    &-title {
      font-size: 26px;
      color: #333;
      font-weight: 600;
    }
    &-tip {
      font-size: 18px;
      color: #666;
      margin-top: 10px;
    }
  }
}
</style>